/**
 * CopyRight ziHou
 * 2019/3/1
 * version : 1.0.0
 */
'use strict';

import Fly from 'flyio/dist/npm/wx';
// import Fly from 'flyio' // 引用失败

// 获取白名单
import whiteList from '@/utils/whiteList';

const fly = new Fly();

//设置超时
fly.config.timeout = 20000;

// const Authorization = wx.getStorageSync('Authorization');

//添加请求拦截器
fly.interceptors.request.use((request) => {
  console.log('request', request);
  // 不显示加载页面的接口
  if (whiteList.loading.indexOf(request.url) === -1) {
    // 隐藏loading遮罩
  }
  wx.showLoading({
    'title': '加载中',
    'mask': true
  });
  // 请求资源服务器时，不添加token
  if (whiteList.nullHeaderToken.indexOf(request.url) !== -1) {
    request.timeout = 30000; // 请求超时
    request.headers = {
      'content-type': 'application/json',
      'X-Tag': 'flyio'
    };
    return request;
  }
  const Authorization = wx.getStorageSync('Authorization');
  // 延迟发请求 等 getStorageSync 存储
  setTimeout(() => {
    // 无token 则跳转登陆页
    if (Authorization) {
      // 给所有请求添加自定义header
      request.timeout = 30000;
      request.headers = {
        'content-type': 'application/json',
        'X-Tag': 'flyio',
        'Authorization': 'Bearer ' + Authorization
      };
    } else {
      // promise.reject(request)
      console.log('没有token跳转登录');
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/main'
        });
      }, 300)
    }
    return request;
  }, 300)
}, (error,promise) => {
  // Do something with request error
  console.log(error); // for debug
  promise.reject(error)
});

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    wx.hideLoading();
    console.log('interceptors数据', response.data);
    //只将请求结果的data字段返回
    return response.data
  },
  (err, promise) => {
    wx.hideLoading();
    let msg = '';
    if (err.status === 0) {
      msg = '网络连接异常'
    } else if (err.status === 1) {
      msg = '网络连接超时'
    } else if (err.status === 401) {
      msg = '用户未登录'
    } else {
      if (err.response.data.message) {
        msg = err.response.data.message
      } else {
        msg = '请求数据失败,请稍后再试'
      }
    }
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000
    });
    return promise.resolve(err)
  }
);
// Vue.prototype.$http=fly //将fly实例挂在vue原型上

export default fly
